package com.yjz.jvm.反射.jdk7方法句柄;

import lombok.SneakyThrows;
import org.junit.Test;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class 句柄测试 {
    @SneakyThrows
    @Test
    public void 句柄测试() {
        User user = new User("张三");

        MethodHandles.Lookup lookup = MethodHandles.lookup();

        MethodHandle speckMethodHandle = lookup.findVirtual(User.class, "speck", MethodType.methodType(void.class, String.class));

        speckMethodHandle.invokeExact(user, "今天天气不错");

        //私有方法不能再外面这样调用,会报错，因为没有访问权限
        //详见:https://www.v2ex.com/t/671606#reply8
        MethodHandle singMethodHandle = lookup.findSpecial(User.class, "sing", MethodType.methodType(void.class), User.class);

        singMethodHandle.invokeExact(user);

        //通过public方法获取私有方法句柄
        MethodHandle  privateMethodHandle =user.getSingMethodHandle();

        //私有方法句柄可以被调用成功
        privateMethodHandle.invoke(user);

    }
}
